<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库区名称" prop="locationName">
        <el-input
          v-model="queryParams.locationName"
          placeholder="请输入库区名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['location:location:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['location:location:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['location:location:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['location:location:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="locationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库区编码" align="center" prop="locationCode" width="200px"/>
      <el-table-column label="库区名称" align="center" prop="locationName" />
      <el-table-column label="面积" align="center" prop="area" />
      <el-table-column label="是否冻结" align="center" prop="areaFlag" >
        <template #default="scope">
          <el-switch 
            v-model="scope.row.areaFlag" 
            active-value="N"
            inactive-value="Y"
            active-text="是" 
            inactive-text="否"
            @change="handleEnableChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template #default="scope">
             <el-button link type="primary" icon="Shop" @click="region(scope.row)" >库位</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['location:location:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['location:location:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库区对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body @close="resetDialogForm">
      <el-form ref="locationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库区编码" prop="locationCode">
          <el-input v-model="form.locationCode" placeholder="请输入库区编码" />
          <!-- 自动生成 -->
          <el-switch 
                v-model="autoGenerateCode" 
                style="margin-left: 10px;"
                @change="handleCodeSwitchChange" 
              ></el-switch>
          <span style="margin-left: 5px;">自动生成</span>
        </el-form-item>
        <el-form-item label="库区名称" prop="locationName">
          <el-input v-model="form.locationName" placeholder="请输入库区名称" />
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input v-model="form.area" placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Location">
import { listLocation, getLocation, delLocation, addLocation, updateLocation ,updateLocation1} from "@/api/location/location"

const { proxy } = getCurrentInstance()

const locationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 新增：自动生成编码开关状态
const autoGenerateCode = ref(false)

import { useRoute } from 'vue-router'
const route = useRoute()
//获取当前仓库id
const locationId1 = route.params.locationId 

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    locationName: null,
    warehouseId:0
  },
  rules: {
    locationCode: [
      { required: true, message: "库区编码不能为空", trigger: "blur" }
    ],
    locationName: [
      { required: true, message: "库区名称不能为空", trigger: "blur" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "blur" }
    ],
  }
})
/** 生成库区编码（规则：WS-YYYYMMDDHHmmss，如WS-20240520143025） */
function generateWorkshopCode() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  const code = `KQ-${year}${month}${day}${hour}${minute}${second}`
  form.value.locationCode = code
}

/** 自动生成开关变化事件 */
function handleCodeSwitchChange() {
  if (autoGenerateCode.value) {
    generateWorkshopCode()
  } else {
    form.value.locationCode = null  // 关闭时清空手动输入
    
  }
}

// 表单ref（与模板中ref="warehouseRef"对应）
const warehouseRef = ref();
// 对话框关闭时：重置表单 + 关闭开关
function resetDialogForm() {
  // 关闭“自动生成”开关
  autoGenerateCode.value = false;

  // 清除验证状态
  if (warehouseRef.value) {
    warehouseRef.value.clearValidate(); // 清除所有字段验证
  }
  // 清空表单数据
  data.form = {};
  open.value = false;
}

const { queryParams, form, rules } = toRefs(data)
import { ElMessage, ElMessageBox } from 'element-plus'

//是否启用开关
const handleEnableChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `你确认要${row.areaFlag === 'N' ? '冻结' : '启用'}‘${row.locationName}’仓库吗?`,
      '系统提示',
      {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    );
    // 用户确认后执行更新
    const response = await updateLocation(row);
   console.log(response);
    
    if (response.code==200) {
      ElMessage.success("操作成功");
      getList()
    } else {
      ElMessage.error("操作失败");
      getList()
    }
  } catch (error) {

    // 捕获取消操作异常，恢复原始状态
      getList()
    
  }
};

/** 查询库区列表 */
function getList() {
  loading.value = true
  queryParams.value.warehouseId= parseInt(locationId1)
  listLocation(queryParams.value).then(response => {
    locationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    locationId: null,
    locationCode: null,
    locationName: null,
    warehouseId: null,
    area: null,
    areaFlag: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("locationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.locationId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加库区"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _locationId = row.locationId || ids.value
  getLocation(_locationId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改库区"
  })
}

/** 提交按钮 */
function submitForm() {
  form.value.warehouseId=locationId1
  // console.log(form);
  
  proxy.$refs["locationRef"].validate(valid => {
    if (valid) {
      if (form.value.locationId != null) {
        updateLocation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLocation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _locationIds = row.locationId || ids.value
  proxy.$modal.confirm('是否确认删除库区编号为"' + _locationIds + '"的数据项？').then(function() {
    return delLocation(_locationIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('location/location/export', {
    ...queryParams.value
  }, `location_${new Date().getTime()}.xlsx`)
}


import { useRouter } from 'vue-router'//进行路由跳转
const router=useRouter()
//跳转到库位
function region(row){
  //console.log(row);
    
  router.push(`/storage/area/${row.locationId}`)

}

getList()
</script>
